<template>
  <div class="department-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span>部门管理 /</span>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="showAddDialog">+ 添加部门</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="部门名称：">
          <el-input v-model="searchForm.name" placeholder="请输入部门名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="部门状态：">
          <el-select v-model="searchForm.status" placeholder="请选择部门状态" clearable>
            <el-option label="正常" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="departmentList" stripe style="width: 100%" height="calc(100vh - 400px)">
        <el-table-column prop="index" label="序号" width="80" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="部门名称" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后修改时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="action" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button type="text" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button type="text" @click="showDeleteDialog(scope.row.id)" style="color: #ff4d4f">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 添加/编辑部门模态框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="closeDialog"
    >
      <el-form :model="formData" :rules="formRules" ref="departmentForm" label-width="100px">
        <el-form-item label="部门名称：" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="部门状态：" prop="status">
          <el-select v-model="formData.status" placeholder="请选择部门状态">
            <el-option label="正常" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="删除确认"
      v-model="deleteDialogVisible"
      width="300px"
    >
      <span>确定要删除该部门吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList, addDepartment, updateDepartment, deleteDepartment } from '@/api/department'

export default {
  name: 'DepartmentView',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        status: ''
      },
      // 部门列表
      departmentList: [],
      // 总记录数
      total: 0,
      // 当前页码
      currentPage: 1,
      // 每页条数
      pageSize: 10,
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '添加部门',
      formData: {
        id: '',
        name: '',
        status: 1
      },
      formRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称长度应在2-10位之间', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择部门状态', trigger: 'change' }
        ]
      },
      // 删除确认对话框
      deleteDialogVisible: false,
      deleteId: ''
    }
  },
  mounted() {
    this.loadDepartmentList()
  },
  methods: {
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      if (isNaN(date.getTime())) return dateTime
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    
    // 加载部门列表
    async loadDepartmentList() {
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        }
        
        const response = await getDepartmentList(params)
        
        if (response.code === 1) {
          this.departmentList = response.data.rows || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.msg || '获取部门列表失败')
          this.departmentList = []
          this.total = 0
        }
      } catch (error) {
        this.$message.error('获取部门列表失败，请稍后重试')
        this.departmentList = []
        this.total = 0
      }
    },
    
    // 搜索
    search() {
      this.currentPage = 1
      this.loadDepartmentList()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        status: ''
      }
      this.currentPage = 1
      this.loadDepartmentList()
    },
    
    // 显示添加对话框
    showAddDialog() {
      this.dialogTitle = '添加部门'
      this.formData = {
        id: '',
        name: '',
        status: 1
      }
      this.dialogVisible = true
    },
    
    // 显示编辑对话框
    showEditDialog(row) {
      this.dialogTitle = '修改部门'
      this.formData = {
        id: row.id,
        name: row.name,
        status: row.status
      }
      this.dialogVisible = true
    },
    
    // 关闭对话框
    closeDialog() {
      this.dialogVisible = false
      this.$refs.departmentForm.resetFields()
    },
    
    // 提交表单
    async submitForm() {
      this.$refs.departmentForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.formData.id) {
              // 编辑
              const response = await updateDepartment(this.formData)
              if (response.code === 1) {
                this.$message.success('修改成功')
                this.closeDialog()
                this.loadDepartmentList()
              } else {
                this.$message.error(response.msg || '修改失败')
              }
            } else {
              // 添加
              const response = await addDepartment(this.formData)
              if (response.code === 1) {
                this.$message.success('添加成功')
                this.closeDialog()
                this.loadDepartmentList()
              } else {
                this.$message.error(response.msg || '添加失败')
              }
            }
          } catch (error) {
            this.$message.error('操作失败，请稍后重试')
          }
        }
      })
    },
    
    // 显示删除确认对话框
    showDeleteDialog(id) {
      this.deleteId = id
      this.deleteDialogVisible = true
    },
    
    // 确认删除
    async confirmDelete() {
      try {
        const response = await deleteDepartment(this.deleteId)
        if (response.code === 1) {
          this.$message.success('删除成功')
          this.deleteDialogVisible = false
          this.loadDepartmentList()
        } else {
          this.$message.error(response.msg || '删除失败')
        }
      } catch (error) {
        this.$message.error('删除失败，请稍后重试')
      }
    },
    
    // 分页相关
    handleSizeChange(size) {
      this.pageSize = size
      this.loadDepartmentList()
    },
    handleCurrentChange(current) {
      this.currentPage = current
      this.loadDepartmentList()
    }
  }
}
</script>

<style scoped>
.department-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
  color: #606266;
}

.operation-area {
  margin-bottom: 20px;
}

.search-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form .el-form-item {
  margin-right: 20px;
}

.table-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination-area {
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end;
  margin-top: -20px;
}

  /* 表格内容居中 */
  .el-table .el-table__cell {
    text-align: center;
  }
</style>